import datetime
from django_redis import get_redis_connection
from rest_framework import serializers
from django.db import transaction
import time
from areas.models import Area
from users.models import User, Address
from .models import OrderInfo, OrderGoods, DiscountCoupon, Courier_Company, ReturnDetail, ReturnDetailImage, \
    Business_Address, GoodsList, Reason
from goods.models import Goods, Brand, GoodsCategory, GoodsAttribute, DiscountPackage
from random import Random
from tasks import check_orderinfo


class Goodsdetail_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ('name',)


class CartgoodsSerializer(serializers.ModelSerializer):
    """购物车商品"""
    count = serializers.IntegerField()
    selected = serializers.BooleanField()
    goods = Goodsdetail_Serializer()

    class Meta:
        model = GoodsAttribute
        fields = ('id', 'goods_code', 'color', 'image', 'size', 'price', 'goods', 'selected', 'count',)
        read_only_fields = ('goods_code', 'color', 'image', 'size', 'price', 'goods', 'count', 'selected')


class OrderSettlementSerializer(serializers.Serializer):
    """订单确认"""
    Goods_list = CartgoodsSerializer(many=True, read_only=True)


class DiscountCouponSerialier(serializers.ModelSerializer):
    class Meta:
        model = DiscountCoupon
        fields = ('name', "value", 'full',)


class SaveOrderSerializer(serializers.ModelSerializer):
    """购物车生成订单的序列化器"""
    discountcoupon = DiscountCouponSerialier(read_only=True, )
    discountcoupon_id = serializers.IntegerField(write_only=True, allow_null=True,required=False)
    address = serializers.IntegerField(write_only=True, min_value=1, required=False)
    pay_method = serializers.IntegerField(default=1, )
    courier_company = serializers.IntegerField(write_only=True, min_value=1, required=True)

    class Meta:
        model = OrderInfo
        fields = ('order_id', 'total_amount', 'total_count', 'address',
                  'pay_method', 'freight', 'courier_company', 'discountcoupon', 'discountcoupon_id',)
        read_only_fields = ('order_id', 'total_amount', 'total_count', 'discountcoupon',
                            'freight',)

    def create(self, validated_data):
        user = self.context['request'].user
        random_ins = Random()
        order_id = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       userid=self.context["request"].user.id,
                                                       ranstr=random_ins.randint(10, 99))
        address = validated_data['address']
        pay_method = validated_data['pay_method']
        courier_company = validated_data['courier_company']
        discountcoupon_id = validated_data['discountcoupon_id']#None
        try:
            address = Address.objects.get(id=address, user=user)
        except:
            raise serializers.ValidationError('请正确的选择收货地址')
        courier_company = Courier_Company.objects.get(id=courier_company)

        if discountcoupon_id:  # 优惠券处理，判断是否携带优惠券过来
            dis = DiscountCoupon.objects.get(id=discountcoupon_id,)
            if dis.category in [1,2]:
                try:
                    discountcoupon_low = DiscountCoupon.objects.get(id=discountcoupon_id, user=None)  # 查找该种类优惠券模板
                except:
                    raise serializers.ValidationError('商城没有该种类优惠券')
                try:
                    discountcoupon = DiscountCoupon.objects.get(user=user, name=discountcoupon_low.name,category__in=[1,2])  # 与用户绑定的优惠券
                except:
                    raise serializers.ValidationError('该用户没有领取该种优惠券')
                if discountcoupon.status:
                    raise serializers.ValidationError('该优惠券已使用过')
                if discountcoupon.start_time > datetime.date.today() or discountcoupon.end_time < datetime.date.today():
                    raise serializers.ValidationError('请于设定时间使用该优惠券')
                value = discountcoupon.value
            elif dis.category==3 and dis.user == user:  # 携带个人专享优惠券检验使用用户是否是指定用户
                value = dis.value
                discountcoupon =dis
                discountcoupon_low = None
            else:
                raise serializers.ValidationError('该优惠券不可使用')
        else:  # 如果没有优惠券对变量赋值
            value = 0
            discountcoupon = None
            discountcoupon_low = None
        with transaction.atomic():  # 开启事务
            # 创建保存点，记录当前数据状态
            save_id = transaction.savepoint()
            try:
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=address,
                    pay_method=pay_method,
                    courier_company=courier_company,
                    discountcoupon=discountcoupon,
                )
                # 从redis中获取购物车数据
                redis_conn = get_redis_connection('cart')
                cart_redis = redis_conn.hgetall('cart_%s' % user.id)
                cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)
                cart = {}
                for goods_id in cart_selected:
                    cart[int(goods_id)] = int(cart_redis[goods_id])
                goods_id_list = cart.keys()
                if len(goods_id_list) == 0:
                    raise serializers.ValidationError('请先向购物车添加商品')
                # 遍历勾选要下单的商品数据，
                a = 0  # 临时变量，用于判断该订单所有商品是否与优惠券使用范围产生交集
                freight_list = []
                for goods_id in goods_id_list:
                    while True:
                        try:
                            goods = GoodsAttribute.objects.get(id=goods_id)
                        except:
                            raise serializers.ValidationError('该商品已下架，请先将该商品移出购物车')
                        if discountcoupon:
                            if discountcoupon.category in [1,2]:
                                if discountcoupon_low.category == 1:
                                    a = 1
                                elif discountcoupon_low.category == 2:
                                    if (discountcoupon.category_brand == goods.goods.brand) \
                                            or (discountcoupon.category_category == goods.goods.category):
                                        a = 1
                                    discountcoupon_low_list = GoodsList.objects.filter(
                                        discountcoupon_id=discountcoupon_low)
                                    for coupon in discountcoupon_low_list:
                                        if coupon.cate_goods == goods.goods:
                                            a = 1
                            elif discountcoupon.category == 3:
                                discountcoupon_list = GoodsList.objects.filter(
                                    discountcoupon_id=discountcoupon)
                                for coupon in discountcoupon_list:
                                    if coupon.cate_goods == goods.goods:
                                        a = 1
                        count = cart[goods.id]  # 该商品下单数量
                        stock = goods.storage_amout  # 商品库存量
                        goods_inlaw = Goods.objects.get(name=goods.goods)
                        sold = goods_inlaw.sold_num
                        if stock < count:  # 判断商品库存是否充足
                            transaction.savepoint_rollback(save_id)  # 事务回滚
                            raise serializers.ValidationError('商品库存不足')
                        if not goods_inlaw.ship_free:  # 判断是否包邮
                            freight_list.append(goods.weight*courier_company.price)
                        else:
                            freight_list.append(0)
                        # 变更数据库库存和销量
                        new_stock = stock - count
                        new_sales = sold + count
                        """销售量针对商品进行处理"""
                        ret_1 = Goods.objects.filter(name=goods.goods, sold_num=sold).update(sold_num=new_sales)
                        if ret_1 == 0:
                            continue
                        """库存量针对商品属性进行处理"""
                        ret_2 = GoodsAttribute.objects.filter(id=goods.id, storage_amout=stock).update(
                            storage_amout=new_stock)
                        if ret_2 == 0:
                            continue
                        order.total_count += count
                        order.total_amount += goods.price * count
                        # 保存到OrderGoods
                        OrderGoods.objects.create(
                            order=order,
                            goods=goods,
                            count=count,
                            price=goods.price,
                        )
                        break
                # 购物车商品处理完成后，需针对优惠券处理
                if discountcoupon:
                    if a != 1:
                        raise serializers.ValidationError('该优惠券不适用于该笔订单商品')
                    if discountcoupon.category in [1,2]:
                        discountcoupon.status = True  # 该张与用户绑定优惠券变更为已使用
                        discountcoupon.is_show = False  # 该张与用户绑定优惠券变更为不向客户展示
                        discountcoupon.used_time = datetime.datetime.now()
                        discountcoupon_low.used_counts += 1  # 该张优惠券使用量增加一个
                        if order.total_amount < discountcoupon_low.full:
                            raise serializers.ValidationError('该优惠券满减值不符合要求')
                        discountcoupon_low.save()
                    elif discountcoupon.category ==3:
                        if order.total_amount < discountcoupon.full:
                            raise serializers.ValidationError('该优惠券满减值不符合要求')
                        discountcoupon.is_show = False
                        discountcoupon.status = True
                        discountcoupon.used_time = datetime.datetime.now()
                        discountcoupon.used_counts = 1
                    discountcoupon.save()
                order.discount_value = value
                freight = min(freight_list)
                order.total_amount = order.total_amount + freight - value
                order.total_amount -= value
                order.freight = freight
                order.save()
                # 调用异步任务，将订单编号传入异步队列
                check_orderinfo.delay(order.order_id)
                transaction.savepoint_commit(save_id)
            except serializers.ValidationError:
                transaction.savepoint_rollback(save_id)
                raise
        # 清除购物车中已经结算的商品
        pl = redis_conn.pipeline()
        pl.hdel('cart_%s' % user.id, *cart_selected)
        pl.srem('cart_selected_%s' % user.id, *cart_selected)
        pl.execute()
        return order


class GoodsDetailSerializer(serializers.ModelSerializer):
    """商品详情页面生成订单"""
    discountcoupon = DiscountCouponSerialier(read_only=True, )
    discountcoupon_id = serializers.IntegerField(write_only=True, allow_null=True,required=False)
    address = serializers.IntegerField(write_only=True, min_value=1, required=True)
    pay_method = serializers.IntegerField(default=1, )
    courier_company = serializers.IntegerField(write_only=True, min_value=1, required=True)
    goodsattribute_id = serializers.IntegerField(write_only=True, min_value=1, required=True)
    count = serializers.IntegerField(write_only=True, min_value=1, required=True)

    class Meta:
        model = OrderInfo
        fields = ('order_id', 'total_amount', 'total_count', 'address', 'goodsattribute_id', 'count',
                  'pay_method', 'freight', 'courier_company', 'discountcoupon', 'discountcoupon_id',)
        read_only_fields = ('order_id', 'total_amount', 'total_count', 'discountcoupon',
                            'freight',)

    def create(self, validated_data):
        user = self.context['request'].user
        random_ins = Random()
        order_id = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       userid=user.id,
                                                       ranstr=random_ins.randint(10, 99))
        address = validated_data['address']
        pay_method = validated_data['pay_method']
        courier_company_id = validated_data['courier_company']
        discountcoupon_id = validated_data['discountcoupon_id']
        goods_id = validated_data['goodsattribute_id']
        count = validated_data['count']
        try:
            address = Address.objects.get(id=address, user=user)
        except:
            raise serializers.ValidationError('请正确的选择收货地址')
        courier_company = Courier_Company.objects.get(id=courier_company_id)

        if discountcoupon_id:  # 优惠券处理，判断是否携带优惠券过来
            dis = DiscountCoupon.objects.get(id=discountcoupon_id,)
            if dis.category in [1,2]:
                try:
                    discountcoupon_low = DiscountCoupon.objects.get(id=discountcoupon_id, user=None)  # 查找该种类优惠券模板
                except:
                    raise serializers.ValidationError('商城没有该种类优惠券')
                try:
                    discountcoupon = DiscountCoupon.objects.get(user=user, name=discountcoupon_low.name)  # 与用户绑定的优惠券
                except:
                    raise serializers.ValidationError('该用户没有领取该种优惠券')
                if discountcoupon.status:
                    raise serializers.ValidationError('该优惠券已使用过')
                if discountcoupon.start_time > datetime.date.today() or discountcoupon.end_time < datetime.date.today():
                    raise serializers.ValidationError('请于设定时间使用该优惠券')
                value = discountcoupon.value
            elif dis.category==3 and dis.user == user:  # 携带个人专享优惠券检验使用用户是否是指定用户
                value = dis.value
                discountcoupon =dis
                discountcoupon_low = None
            else:
                raise serializers.ValidationError('该优惠券不可使用')
        else:
            value = 0
            discountcoupon = None
            discountcoupon_low = None
        # if discountcoupon_id:
        #     discountcoupon_low = DiscountCoupon.objects.get(id=discountcoupon_id, user=None)  # 查找该种类优惠券模板
        #     discountcoupon = DiscountCoupon.objects.get(user=user, name=discountcoupon_low.name)  # 该种类优惠券模板
        #     if discountcoupon.status == True:
        #         raise serializers.ValidationError('该优惠券已使用过')
        #     if discountcoupon.start_time > datetime.date.today() or discountcoupon.end_time < datetime.date.today():
        #         raise serializers.ValidationError('请于设定时间使用该优惠券')
        #     value = discountcoupon.value
        # else:
        #     value = 0
        #     discountcoupon = None
        #     discountcoupon_low = None
        with transaction.atomic():  # 开启事务
            # 创建保存点，记录当前数据状态
            save_id_1 = transaction.savepoint()
            try:
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=address,
                    courier_company=courier_company,
                    pay_method=pay_method,
                    discountcoupon=discountcoupon,
                )
                a = 0
                while True:
                    try:
                        goods = GoodsAttribute.objects.get(id=goods_id)  # 前端传参找到要下单的商品属性对象
                    except:
                        raise serializers.ValidationError('商品属性id传参有误')
                    goods_inlaw = Goods.objects.get(name=goods.goods.name)  # 找到对应商品对象

                    if discountcoupon:
                        if discountcoupon.category in [1, 2]:
                            if discountcoupon_low.category == 1:
                                a = 1
                            elif discountcoupon_low.category == 2:
                                if (discountcoupon.category_brand == goods.goods.brand) \
                                        or (discountcoupon.category_category == goods.goods.category):
                                    a = 1
                                discountcoupon_low_list = GoodsList.objects.filter(
                                    discountcoupon_id=discountcoupon_low)
                                for coupon in discountcoupon_low_list:
                                    if coupon.cate_goods == goods.goods:
                                        a = 1
                        elif discountcoupon.category == 3:
                            discountcoupon_list = GoodsList.objects.filter(
                                discountcoupon_id=discountcoupon)
                            for coupon in discountcoupon_list:
                                if coupon.cate_goods == goods.goods:
                                    a = 1

                    # if discountcoupon:
                    #     if discountcoupon_low.category == 1:
                    #         a = 1
                    #     elif discountcoupon_low.category == [2, 3]:
                    #         if (discountcoupon.category_brand == goods.goods.brand) \
                    #                 or (discountcoupon.category_category == goods.goods.category):
                    #             a = 1
                    #         discountcoupon_low_list = GoodsList.objects.filter(discountcoupon_id=discountcoupon_low.id)
                    #         for coupon in discountcoupon_low_list:
                    #             if coupon.cate_goods == goods.goods:
                    #                 a = 1

                    stock = goods.storage_amout  # 商品库存量
                    freight = 0
                    if not goods_inlaw.ship_free:
                        freight = goods.weight * courier_company.price
                    order.freight = freight
                    sold = goods_inlaw.sold_num
                    if count > stock:  # 下单数量大于商品库存
                        transaction.savepoint_rollback(save_id_1)  # 事务回滚
                        raise serializers.ValidationError('商品库存不足')
                        # 变更数据库数据
                    new_stock = stock - count
                    new_sales = sold + count
                    ret_1 = Goods.objects.filter(name=goods.goods, sold_num=sold).update(sold_num=new_sales)  # 销售量变更
                    if ret_1 == 0:
                        continue
                    ret_2 = GoodsAttribute.objects.filter(id=goods.id, storage_amout=stock, ).update(
                        storage_amout=new_stock, )  # 库存量变更
                    if ret_2 == 0:
                        continue
                    order.total_count = count
                    order.total_amount = goods.price * count
                    # 保存到OrderGoods
                    from orders.models import OrderGoods
                    OrderGoods.objects.create(
                        order=order,
                        goods=goods,
                        count=count,
                        price=goods.price,
                    )
                    break

                if discountcoupon:
                    if a != 1:
                        raise serializers.ValidationError('该优惠券不适用于该笔订单商品')
                    if discountcoupon.category in [1,2]:
                        discountcoupon.status = True  # 该张与用户绑定优惠券变更为已使用
                        discountcoupon.is_show = False  # 该张与用户绑定优惠券变更为不向客户展示
                        discountcoupon.used_time = datetime.datetime.now()
                        discountcoupon_low.used_counts += 1  # 该张优惠券使用量增加一个
                        if order.total_amount < discountcoupon_low.full:
                            raise serializers.ValidationError('该优惠券满减值不符合要求')
                        discountcoupon_low.save()
                    elif discountcoupon.category ==3:
                        if order.total_amount < discountcoupon.full:
                            raise serializers.ValidationError('该优惠券满减值不符合要求')
                        discountcoupon.is_show = False
                        discountcoupon.status = True
                        discountcoupon.used_time = datetime.datetime.now()
                        discountcoupon.used_counts = 1
                    discountcoupon.save()

                # if discountcoupon:
                #     if a != 1:
                #         raise serializers.ValidationError('该优惠券不适用于该笔订单商品')
                #     discountcoupon.status = True  # 该张与用户绑定优惠券变更为已使用
                #     discountcoupon.is_show = False  # 该张与用户绑定优惠券变更为不向客户展示
                #     discountcoupon.used_time = datetime.datetime.now()
                #     discountcoupon_low.used_counts += 1  # 该张优惠券使用量增加一个
                #     if order.total_amount < discountcoupon_low.full:
                #         transaction.savepoint_rollback(save_id_1)
                #         raise serializers.ValidationError('该优惠券满减值不符合')
                #     discountcoupon.save()
                #     discountcoupon_low.save()

                order.total_amount = order.total_amount + freight - value
                order.discount_value = value
                order.save()
                # 调用异步任务，将订单编号传入异步队列
                check_orderinfo.delay(order.order_id)
                transaction.savepoint_commit(save_id_1)
            except Exception:
                transaction.savepoint_rollback(save_id_1)
                raise
        return order


class DiscountPackageSerializer(serializers.ModelSerializer):
    """
    前端传参
    {goods_list:[
    {"goods_id":1,"id":10},
    {"goods_id":2,"id":10}]
    }
    """
    discountpackage_id = serializers.IntegerField(write_only=True, min_value=1, required=True)
    goods_list = serializers.ListField(child=serializers.DictField(), write_only=True, required=True)
    address = serializers.IntegerField(write_only=True, min_value=1, required=True)
    pay_method = serializers.IntegerField(default=1,)
    courier_company = serializers.IntegerField(write_only=True, min_value=1, required=True)

    class Meta:
        model = OrderInfo
        fields = ('order_id', 'total_amount', 'total_count', 'address', 'discountpackage_id', 'goods_list',
                  'pay_method', 'courier_company',)
        read_only_fields = ('order_id', 'total_amount', 'total_count',)

    def create(self, validated_data):
        user = self.context['request'].user
        random_ins = Random()
        address = validated_data['address']
        pay_method = validated_data['pay_method']
        courier_company_id = validated_data['courier_company']
        discountpackage_id = validated_data['discountpackage_id']
        goods_list_old = validated_data['goods_list']
        goods_list = [i['id'] for i in goods_list_old]
        order_id = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       userid=user.id,
                                                       ranstr=random_ins.randint(10, 99))
        try:
            address = Address.objects.get(id=address, user=user)
        except:
            raise serializers.ValidationError('请正确的选择收货地址')
        courier_company = Courier_Company.objects.get(id=courier_company_id)
        discountpackage = DiscountPackage.objects.get(id=discountpackage_id)
        """验证传过来的商品属性id是否对应该套餐相应商品"""
        goods_list_low = discountpackage.goods.all()  # 取出对应优惠套餐包含的商品查询集
        id_low_list = [i.id for i in goods_list_low]
        id_list = []
        for a in goods_list:
            try:
                id = GoodsAttribute.objects.get(id=a).goods.id
            except:
                raise serializers.ValidationError('请求商品不存在')
            id_list.append(id)
        if sorted(id_low_list) != sorted(id_list):
            raise serializers.ValidationError('请求商品不在套餐范围内')
        with transaction.atomic():  # 开启事务
            # 创建保存点，记录当前数据状态
            atomic_discountpackage = transaction.savepoint()
            try:
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=address,
                    courier_company=courier_company,
                    pay_method=pay_method,
                )
                for id in goods_list:
                    goodsattribute = GoodsAttribute.objects.get(id=id)  # 商品属性对象
                    goods = Goods.objects.get(name=goodsattribute.goods.name)  # 找到对应商品对象
                    if goodsattribute.storage_amout < 1:
                        transaction.savepoint_rollback(atomic_discountpackage)  # 事务回滚
                        raise serializers.ValidationError('商品库存不足')
                    new_storage_amout = goodsattribute.storage_amout - 1
                    new_sold_num = goods.sold_num + 1
                    ret_1 = Goods.objects.filter(id=goods.id).update(sold_num=new_sold_num)  # 销售量变更
                    ret_2 = GoodsAttribute.objects.filter(id=id).update(storage_amout=new_storage_amout, )  # 库存量变更
                    OrderGoods.objects.create(
                        order=order,
                        goods=goodsattribute,
                        count=1,
                        price=goodsattribute.price,
                    )
                    order.total_count += 1
                    order.total_amount += goodsattribute.price
                order.total_amount -= discountpackage.saved_at_most
                order.discount_value = discountpackage.saved_at_most
                order.discountpackage = discountpackage
                discountpackage.number += 1
                discountpackage.save()
                order.save()
                # 调用异步任务，将订单编号传入异步队列
                check_orderinfo.delay(order.order_id)
                transaction.savepoint_commit(atomic_discountpackage)
            except:
                transaction.savepoint_rollback(atomic_discountpackage)
                raise
        return order


class GoodsSerialier(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ("id", 'name',)


class PackageListSerializer(serializers.ModelSerializer):
    goods =  GoodsSerialier()
    goods_list = serializers.ListField(write_only=True, required=False)
    class Meta:
        model = GoodsAttribute
        fields = ("id","goods_code",'color', "image", 'size',"weight","price","goods","goods_list")


class Create_CouponSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=True)
    """领取优惠券"""

    class Meta:
        model = DiscountCoupon
        fields = ('id',)

    def create(self, validated_data):
        user = self.context['request'].user
        discountcoupon_id = validated_data.get('id')
        coupon = DiscountCoupon.objects.get(id=discountcoupon_id)
        """判断逻辑，1 需要在指定的时间领取优惠券  2，同一个用户同一优惠券只能领取一次，"""
        coupon_list = DiscountCoupon.objects.filter(user=user, ).exclude(category=3)  # 取出所有该用户领取的优惠券
        for coupon_user in coupon_list:
            if coupon_user.name == coupon.name:
                raise serializers.ValidationError({"message": "该用户已领取该种优惠券"})
        if coupon.end_time < datetime.date.today():  # 如果优惠券过期没有主动关闭，会在下次调用时，将优惠券状态更改为对前台不显示
            coupon.is_show = False
            coupon.save()
            raise serializers.ValidationError({"message": "该优惠券已过期，无法领取"})
        with transaction.atomic():  # 开启事务
            save_id_coupon = transaction.savepoint()  # 创建保存点，记录当前数据状态
            try:
                discountcoupon = DiscountCoupon.objects.create(
                    user=user,
                    name=coupon.name,
                    value=coupon.value,
                    start_time=coupon.start_time,
                    end_time=coupon.end_time,
                    issuance_counts=None,
                    status=False,
                    category_brand=coupon.category_brand,
                    category_category=coupon.category_category,
                    full=coupon.full,
                )
                coupon.issuance_counts += 1  # 用户领取量增加1，如果用户领取量与设置领取上限相等，将该优惠券关闭，对前台不显示。
                if coupon.issuance_counts >= coupon.launch_counts:
                    coupon.is_show = False
                coupon.save()
                discountcoupon.save()
                transaction.savepoint_commit(save_id_coupon)  # 事物提交
            except serializers.ValidationError:
                transaction.savepoint_rollback(save_id_coupon)  # 事物回滚
                raise  # 参数校验有误，生成订单失败
        return discountcoupon


class GoodsAttribute_Serialier(serializers.ModelSerializer):
    goods = GoodsSerialier()
    class Meta:
        model = GoodsAttribute
        fields = ('goods', "weight", 'color', 'goods_code', 'size', 'image',)
        read_only_fields = ('goods',)


class Brand_Serialier(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = ("id", 'name',)


class Goods_Serialier(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ("id", 'name',)


class GoodsCategory_Serialier(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ("id", 'name',)


class GoodsList_Serialier(serializers.ModelSerializer):
    cate_goods = Goods_Serialier()

    class Meta:
        model = GoodsList
        fields = ('cate_goods',)


class GetcouponSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    category_brand = Brand_Serialier()
    category_category = GoodsCategory_Serialier()
    goods_list = GoodsList_Serialier(many=True, read_only=True)
    # "name", 'start_time', 'end_time','category_brand','category_category',
    class Meta:
        model = DiscountCoupon
        fields = ("id", "name",  'value', 'start_time', 'end_time', 'create_time', 'update_time', 'category', 'launch_counts',
              "full",'category_brand','category_category', "goods_list")



class ReturnDetailImage_Serialier(serializers.ModelSerializer):
    class Meta:
        model = ReturnDetailImage
        fields = ("image",)


class ReturnDetail_Serialier(serializers.ModelSerializer):
    return_image = ReturnDetailImage_Serialier(many=True, read_only=True)
    apply_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    check_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    class Meta:
        model = ReturnDetail
        fields = ("reason", "introduce", "return_numbers", "return_money", "apply_time", "check_time", "check_results",
                  "check_reason",
                  "return_image",)


class OrderGoodssSerialier(serializers.ModelSerializer):
    """查询订单商品序列化器"""
    goods = GoodsAttribute_Serialier()
    return_reason = ReturnDetail_Serialier(many=True, read_only=True)

    class Meta:
        model = OrderGoods
        fields = ("id", "goods", "price", "count", "is_return", "return_reason",)


class Get_Courier_CompanySerializer(serializers.ModelSerializer):
    """查询快递公司"""

    class Meta:
        model = Courier_Company
        fields = ("id", "name", "price")


class User_serializer(serializers.ModelSerializer):
    """收货地址详情"""

    class Meta:
        model = User
        fields = ("nickname",)


class Area_serializer(serializers.ModelSerializer):
    """省市区划分"""

    class Meta:
        model = Area
        fields = ("name",)


class Address_serializer(serializers.ModelSerializer):
    """收货地址详情"""
    user = User_serializer()
    province = Area_serializer()
    city = Area_serializer()
    district = Area_serializer()
    class Meta:
        model = Address
        fields = ("id", "user", "receiver", "province", "city", "district", "place", "mobile",)


class GetordersSerializer(serializers.ModelSerializer):
    """查询订单序列化器"""
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    send_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    pay_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    success_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    goods = OrderGoodssSerialier(many=True, read_only=True)
    courier_company = Get_Courier_CompanySerializer()
    address = Address_serializer()

    class Meta:
        model = OrderInfo
        fields = (
            "order_id", "transaction_id", "numbers", "total_amount", "freight", "total_count", "post_script",
            'send_time', "pay_time", "success_time",
            "over_time", "discountcoupon", "create_time", "status", "courier_company", "address", "goods",
        )
        read_only_fields = ('goods', "courier_company", "address",)


class LogisticsSerializer(serializers.ModelSerializer):
    return_numbers = serializers.CharField(max_length=64)
    numbers = serializers.CharField(max_length=64)
    company = serializers.CharField(max_length=64)
    check_results = serializers.IntegerField(read_only=True)

    class Meta:
        model = ReturnDetail
        fields = ("return_numbers", "numbers", "check_results", "company")


class BusinessAddressSerialier(serializers.ModelSerializer):
    province = Area_serializer()
    city = Area_serializer()
    district = Area_serializer()

    class Meta:
        model = Business_Address
        fields = ("name", "person", "phone_number", "province", "city", "district", "place",)


class OrderInfoSerialier(serializers.ModelSerializer):
    business_address = BusinessAddressSerialier()

    class Meta:
        model = OrderInfo
        fields = ("order_id", "business_address",)


class OrderGoodsSerialier(serializers.ModelSerializer):
    goods = GoodsAttribute_Serialier()
    order = OrderInfoSerialier()

    class Meta:
        model = OrderGoods
        fields = ("goods", "price", "count", "id", "is_return", "order")


class GetReturnSerializer(serializers.ModelSerializer):
    order_goods_id = OrderGoodsSerialier()

    class Meta:
        model = ReturnDetail
        fields = ("numbers", "company", "check_results", "order_goods_id",)


class ReasonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Reason
        fields = ("return_type", "id", "explain",)


class OrderDiscountSerializer(serializers.ModelSerializer):
    goods_list  = serializers.ListField(write_only=True,required=False)
    class Meta:
        model = DiscountCoupon
        fields = ( "id", "name","value","full","goods_list")
